package com.zynn.common.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.zynn.common.core.constant.UserLoginConstant;
import com.zynn.common.core.constant.WechatConstant;
import com.zynn.common.core.dto.LoginAndRegisterResultDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * 用户登陆中对redis 操作工具类
 *
 * @author 杨岳
 * @date 2018/7/6 16:48
 * @date 2018-07-19 刘凯迁移至公共部分，原user服务未做修改
 */
@Component
public class LoginRedisUtils {

    @Autowired
    private JedisCluster jedisCluster;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 获取redis中存储的seesionkey
     *
     * @param openId
     * @return
     */
    public String getSessionKey(String openId) {
        String sessionKey = jedisCluster.hget(UserLoginConstant.USER_OPENID_SESSION_KEY, openId);
        if (StringUtils.isBlank(sessionKey)) {
            throw new RuntimeException("请先调用code接口");
        }
        String[] split = sessionKey.split("_,_");
        return split[0];
    }

    /**
     * redis存储用户sessionkey
     *  格式   field ：openid
     *  value   openid   "_,_"   时间毫秒值
     * @param map
     */
    public void setSessionKey(Map<String, Object> map) {
        jedisCluster.hset(UserLoginConstant.USER_OPENID_SESSION_KEY, map.get(WechatConstant.OPENID).toString(),
                map.get(WechatConstant.SESSION_KEY).toString() + "_,_" + System.currentTimeMillis());
    }

    /**
     * 解密失败
     */
    public void setAESFail(){
        jedisCluster.hset("encodeData_error", sdf.format(System.currentTimeMillis()), "encodeData解密失败");
    }


    /**
     * 用户登陆成功 添加数据到redis 并设置过期时间
     */

    public void setUserToRedis(LoginAndRegisterResultDTO loginAndRegisterResultDTO){
        String s = JSONObject.toJSONString(loginAndRegisterResultDTO);
        String md5Str = MD5Utils.md5Encrypt(loginAndRegisterResultDTO.getOpenId());
        jedisCluster.set(md5Str,s);
        jedisCluster.expire(md5Str,7*24*60*60);
    }
}
